<template>
  <div class="foods-page">
    <a-page-header
      title="食物管理"
      sub-title="添加、编辑和删除食物"
      @back="() => $router.push('/diet')"
    >
      <template #extra>
        <a-button type="primary" @click="showAddModal">
          添加食物
        </a-button>
      </template>
    </a-page-header>

    <a-card :bordered="false" style="margin-top: 16px">
      <a-form layout="inline" :model="searchForm" @finish="handleSearch">
        <a-form-item name="keyword" label="关键词">
          <a-input
            v-model:value="searchForm.keyword"
            placeholder="食物名称"
            allowClear
          />
        </a-form-item>
        
        <a-form-item name="categoryId" label="分类">
          <a-select
            v-model:value="searchForm.categoryId"
            style="width: 180px"
            placeholder="选择分类"
            allowClear
          >
            <a-select-option v-for="category in categories" :key="category.id" :value="category.id">
              {{ category.name }}
            </a-select-option>
          </a-select>
        </a-form-item>
        
        <a-form-item name="suitable" label="适合糖尿病">
          <a-select
            v-model:value="searchForm.suitable"
            style="width: 120px"
            placeholder="全部"
            allowClear
          >
            <a-select-option :value="1">适合</a-select-option>
            <a-select-option :value="0">不适合</a-select-option>
          </a-select>
        </a-form-item>
        
        <a-form-item>
          <a-button type="primary" html-type="submit">
            搜索
          </a-button>
          <a-button style="margin-left: 8px" @click="resetSearch">
            重置
          </a-button>
        </a-form-item>
      </a-form>

      <a-table
        :columns="columns"
        :data-source="foods"
        :pagination="pagination"
        :loading="loading"
        @change="handleTableChange"
        style="margin-top: 16px"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'image'">
            <img
              v-if="record.image"
              :src="record.image"
              :alt="record.name"
              style="width: 50px; height: 50px; object-fit: cover;"
            />
            <span v-else>无图片</span>
          </template>
          
          <template v-if="column.key === 'suitable'">
            <a-tag :color="record.suitable === 1 ? 'green' : 'red'">
              {{ record.suitable === 1 ? '适合' : '不适合' }}
            </a-tag>
          </template>
          
          <template v-if="column.key === 'action'">
            <a-button type="link" size="small" @click="showEditModal(record)">编辑</a-button>
            <a-divider type="vertical" />
            <a-popconfirm
              title="确定要删除这个食物吗？"
              ok-text="确定"
              cancel-text="取消"
              @confirm="deleteFood(record.id)"
            >
              <a-button type="link" danger size="small">删除</a-button>
            </a-popconfirm>
          </template>
        </template>
      </a-table>
    </a-card>

    <!-- 添加/编辑食物的模态框 -->
    <a-modal
      :visible="modalVisible"
      :title="formMode === 'add' ? '添加食物' : '编辑食物'"
      @cancel="modalVisible = false"
      @ok="handleSubmit"
      :confirmLoading="submitLoading"
    >
      <a-form
        :model="foodForm"
        :rules="rules"
        ref="foodFormRef"
        :label-col="{ span: 6 }"
        :wrapper-col="{ span: 16 }"
      >
        <a-form-item name="name" label="食物名称">
          <a-input v-model:value="foodForm.name" />
        </a-form-item>
        
        <a-form-item name="categoryId" label="分类">
          <a-select v-model:value="foodForm.categoryId" placeholder="选择分类">
            <a-select-option v-for="category in categories" :key="category.id" :value="category.id">
              {{ category.name }}
            </a-select-option>
          </a-select>
        </a-form-item>
        
        <a-form-item name="calories" label="热量(kcal)">
          <a-input-number v-model:value="foodForm.calories" :min="0" style="width: 100%" />
        </a-form-item>
        
        <a-form-item name="carbs" label="碳水(g)">
          <a-input-number v-model:value="foodForm.carbs" :min="0" style="width: 100%" />
        </a-form-item>
        
        <a-form-item name="protein" label="蛋白质(g)">
          <a-input-number v-model:value="foodForm.protein" :min="0" style="width: 100%" />
        </a-form-item>
        
        <a-form-item name="fat" label="脂肪(g)">
          <a-input-number v-model:value="foodForm.fat" :min="0" style="width: 100%" />
        </a-form-item>
        
        <a-form-item name="fiber" label="纤维素(g)">
          <a-input-number v-model:value="foodForm.fiber" :min="0" style="width: 100%" />
        </a-form-item>
        
        <a-form-item name="gi" label="血糖指数">
          <a-input-number v-model:value="foodForm.gi" :min="0" :max="100" style="width: 100%" />
        </a-form-item>
        
        <a-form-item name="unit" label="计量单位">
          <a-input v-model:value="foodForm.unit" placeholder="例如: g, 个, 杯" />
        </a-form-item>
        
        <a-form-item name="weight" label="标准重量(g)">
          <a-input-number v-model:value="foodForm.weight" :min="0" style="width: 100%" />
        </a-form-item>
        
        <a-form-item name="image" label="图片URL">
          <a-input v-model:value="foodForm.image" placeholder="输入图片URL" />
        </a-form-item>
        
        <a-form-item name="suitable" label="适合糖尿病">
          <a-switch v-model:checked="foodForm.suitable" :checked-value="1" :un-checked-value="0" />
        </a-form-item>
        
        <a-form-item name="remark" label="备注">
          <a-textarea v-model:value="foodForm.remark" :rows="3" />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script>
import { defineComponent, ref, reactive, onMounted, computed } from 'vue';
import { message } from 'ant-design-vue';
import axios from 'axios';

export default defineComponent({
  setup() {
    const loading = ref(false);
    const submitLoading = ref(false);
    const modalVisible = ref(false);
    const formMode = ref('add'); // 'add' 或 'edit'
    const foodFormRef = ref(null);
    
    // 食物数据
    const foods = ref([]);
    const categories = ref([]);
    
    // 分页配置
    const pagination = reactive({
      current: 1,
      pageSize: 10,
      total: 0,
      showSizeChanger: true,
      showTotal: (total) => `共 ${total} 条记录`
    });
    
    // 搜索表单
    const searchForm = reactive({
      keyword: '',
      categoryId: undefined,
      suitable: undefined
    });
    
    // 食物表单
    const foodForm = reactive({
      id: null,
      name: '',
      categoryId: undefined,
      calories: 0,
      carbs: 0,
      protein: 0,
      fat: 0,
      fiber: 0,
      gi: 0,
      unit: 'g',
      weight: 100,
      image: '',
      suitable: 1,
      remark: ''
    });
    
    // 表单验证规则
    const rules = {
      name: [{ required: true, message: '请输入食物名称' }],
      categoryId: [{ required: true, message: '请选择分类' }],
      calories: [{ required: true, message: '请输入热量' }],
      unit: [{ required: true, message: '请输入计量单位' }],
      weight: [{ required: true, message: '请输入标准重量' }]
    };
    
    // 表格列定义
    const columns = [
      {
        title: 'ID',
        dataIndex: 'id',
        key: 'id'
      },
      {
        title: '图片',
        dataIndex: 'image',
        key: 'image'
      },
      {
        title: '名称',
        dataIndex: 'name',
        key: 'name'
      },
      {
        title: '分类',
        dataIndex: 'categoryName',
        key: 'categoryName'
      },
      {
        title: '热量(kcal)',
        dataIndex: 'calories',
        key: 'calories'
      },
      {
        title: '碳水(g)',
        dataIndex: 'carbs',
        key: 'carbs'
      },
      {
        title: '适合糖尿病',
        dataIndex: 'suitable',
        key: 'suitable'
      },
      {
        title: '操作',
        key: 'action'
      }
    ];
    
    // 获取食物分类
    const fetchCategories = async () => {
      try {
        const response = await axios.get('/admin/diet/categories');
        if (response.data.code === 0) {
          categories.value = response.data.data;
        }
      } catch (error) {
        console.error('获取食物分类失败', error);
        message.error('获取食物分类失败');
      }
    };
    
    // 获取食物列表
    const fetchFoods = async () => {
      try {
        loading.value = true;
        const params = {
          page: pagination.current,
          pageSize: pagination.pageSize,
          ...searchForm
        };
        
        // 移除undefined或null的属性
        Object.keys(params).forEach(key => {
          if (params[key] === undefined || params[key] === null) {
            delete params[key];
          }
        });
        
        const response = await axios.get('/admin/diet/foods', { params });
        if (response.data.code === 0) {
          const data = response.data.data;
          foods.value = data.list || [];
          pagination.total = data.total || 0;
        } else {
          message.error(response.data.msg || '获取食物列表失败');
        }
      } catch (error) {
        console.error('获取食物列表失败', error);
        message.error('获取食物列表失败');
      } finally {
        loading.value = false;
      }
    };
    
    // 表格变化处理(分页、排序等)
    const handleTableChange = (pag) => {
      pagination.current = pag.current;
      pagination.pageSize = pag.pageSize;
      fetchFoods();
    };
    
    // 搜索处理
    const handleSearch = () => {
      pagination.current = 1;
      fetchFoods();
    };
    
    // 重置搜索
    const resetSearch = () => {
      searchForm.keyword = '';
      searchForm.categoryId = undefined;
      searchForm.suitable = undefined;
      pagination.current = 1;
      fetchFoods();
    };
    
    // 显示添加模态框
    const showAddModal = () => {
      formMode.value = 'add';
      // 重置表单
      Object.keys(foodForm).forEach(key => {
        if (key === 'suitable') {
          foodForm[key] = 1;
        } else if (key === 'unit') {
          foodForm[key] = 'g';
        } else if (key === 'weight') {
          foodForm[key] = 100;
        } else if (key === 'id') {
          foodForm[key] = null;
        } else if (typeof foodForm[key] === 'number') {
          foodForm[key] = 0;
        } else {
          foodForm[key] = '';
        }
      });
      modalVisible.value = true;
    };
    
    // 显示编辑模态框
    const showEditModal = (record) => {
      formMode.value = 'edit';
      // 填充表单
      Object.keys(foodForm).forEach(key => {
        if (record[key] !== undefined) {
          foodForm[key] = record[key];
        }
      });
      modalVisible.value = true;
    };
    
    // 提交表单
    const handleSubmit = async () => {
      try {
        await foodFormRef.value.validate();
        submitLoading.value = true;
        
        let response;
        if (formMode.value === 'add') {
          response = await axios.post('/admin/diet/foods', foodForm);
        } else {
          response = await axios.put(`/admin/diet/foods/${foodForm.id}`, foodForm);
        }
        
        if (response.data.code === 0) {
          message.success(formMode.value === 'add' ? '添加成功' : '更新成功');
          modalVisible.value = false;
          fetchFoods();
        } else {
          message.error(response.data.msg || (formMode.value === 'add' ? '添加失败' : '更新失败'));
        }
      } catch (error) {
        console.error(formMode.value === 'add' ? '添加失败' : '更新失败', error);
        message.error(formMode.value === 'add' ? '添加失败' : '更新失败');
      } finally {
        submitLoading.value = false;
      }
    };
    
    // 删除食物
    const deleteFood = async (id) => {
      try {
        loading.value = true;
        const response = await axios.delete(`/admin/diet/foods/${id}`);
        if (response.data.code === 0) {
          message.success('删除成功');
          fetchFoods();
        } else {
          message.error(response.data.msg || '删除失败');
        }
      } catch (error) {
        console.error('删除失败', error);
        message.error('删除失败');
      } finally {
        loading.value = false;
      }
    };
    
    onMounted(() => {
      fetchCategories();
      fetchFoods();
    });
    
    return {
      loading,
      submitLoading,
      modalVisible,
      formMode,
      foodFormRef,
      foods,
      categories,
      pagination,
      searchForm,
      foodForm,
      rules,
      columns,
      handleTableChange,
      handleSearch,
      resetSearch,
      showAddModal,
      showEditModal,
      handleSubmit,
      deleteFood
    };
  }
});
</script>

<style scoped>
.foods-page {
  margin: 0 16px;
}
</style> 